"""封装mysql """

import pymysql
import yaml
from pymysql.cursors import DictCursor

from config.setting import config


class DBHandler():
    def __init__(self, host, port, user, password, charset, database):
        # 要用关键字参数，因为参数是有很多的
        self.conn = pymysql.connect(host=host, port=port,
                                    user=user, password=password,
                                    charset=charset, database=database,
                                    cursorclass=DictCursor)
        # 游标
        self.coursor = self.conn.cursor()
    def query(self, sqlquery, arg=None, one=True):

        # 查询
        self.coursor.execute(sqlquery, args=arg)
        # todo  commit()提交事务，相当于 对数据库增删查改后，后面的操作可以 在这个基础上直接操作
        # 不用怕 用同一个游标 多次查询结果一样
        self.conn.commit()
        # 结果
        if one:
            return self.coursor.fetchone()
        else:
            return self.coursor.fetchall()

    def dbclose(self):
        # 关闭
        self.coursor.close()
        self.conn.close()


if __name__ == '__main__':
    with open(config.yaml_path) as f:
        data = yaml.load(f.read(), Loader=yaml.FullLoader)
    db = DBHandler(host=data['DBdatabase']['host'],
                   port=data['DBdatabase']['port'],
                   user=data['DBdatabase']['user'],
                   password=data['DBdatabase']['password'],
                   charset=data['DBdatabase']['charset'],
                   database=data['DBdatabase']['database']
                   )
    qu = db.query('SELECT * FROM menber')
    print(qu)
    db.dbclose()

    # print(data['DBdatabase']['port'])
